<?php

namespace App\Http\Controllers;

use App\Http\Requests\CategoryRequest;
use App\Models\Cashflow;
use App\Models\Category as Model;
use App\Models\Category;
use Iamxcd\LaravelCRUD\Traits\HasCrud;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    use HasCrud;

    public function __construct(Model $model)
    {
        $this->model = $model;
        $this->request = app(CategoryRequest::class);
    }

    public function appIndex()
    {
        $request = $this->request;
        $params = $request->validated();

        $data = $this->model::query()
            ->where('type', $params['type'])
            ->get();

        return $this->response($data);
    }

    public function appDel($id)
    {
        $exists = Cashflow::query()
            ->where('category_id', $id)->exists();
        if ($exists) {
            return $this->responseError('当前分类，已在账单中使用，不能删除');
        }

        Category::query()->where('id', $id)->delete();
        return $this->responseMessage('删除成功');
    }

    public function appUpdate()
    {
        $request = $this->request;
        $params = $request->validated();
        $category = Category::query()->find($params['id']);

        if (is_null($category)) {
            return $this->responseError('更新失败 种类不存在');
        }
        $category->update($params);
        $this->responseMessage('更新成功');
    }

    public function appStore()
    {
        $request = $this->request;
        $params = $request->validated();
        $this->model::query()->create($params);
        $this->responseMessage('新增成功');
    }
}
